//
//  UITextView + emoticons.swift
//  emoticonView
//
//  Created by 武莎莎 on 15/9/16.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

extension UITextView {
    
    var emoticonText:String {
        let attrText = attributedText
        
        var strM = String()
        // 遍历整个属性文本
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: [], usingBlock: { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? WSEmoticonAttachment {
                strM += attachment.chs
            }else {
                let str = (attrText.string as NSString).substringWithRange(range)
                strM += str
            }
        })
        print(strM)
        return strM
    }
    
    // 点击表情在textView中插入表情符号
    func insertEmoticon(emoticon:WSEmoticons) {
        //点击的是空表情
        if emoticon.isEmpty {
            return
        }
        // 删除按钮
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        // emoji
        if emoticon.emoji != nil {
            // 用emoji替换选中的文本
            replaceRange(self.selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        let imageText = WSEmoticonAttachment.emoticonAttributeText(emoticon, font: font!)
        // 从textView中取出属性文本
        let attrTextM = NSMutableAttributedString(attributedString: self.attributedText)
        // 插入图片文字
        attrTextM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        // 记录光标的位置
        let range = selectedRange
        
        attributedText = attrTextM
        /// 恢复光标的设置,在输入的后面
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}
